//
//  UIWebView+JavaScript.m
//  yunlehui
//
//  Created by saxon on 15/9/20.
//  Copyright (c) 2015年 saxon. All rights reserved.
//

#import "UIWebView+JavaScript.h"
#import <objc/runtime.h>
#import "LALoginViewController.h"




@implementation UIWebView (JavaScript)
static BOOL diagStat = NO;

-(void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame{
    
    
    NSDictionary *alertDic = [RTToolObject dicWithJsonString:message];
    if (alertDic == nil && [message hasValue]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
    if ([alertDic allKeys].count) {
        if ([[alertDic objectForKey:@"type"] isEqualToString:@"loginup"]) {
            
            LALoginViewController *loginVc = [[LALoginViewController alloc] init];
            if (self.jsDelegate && [self.jsDelegate respondsToSelector:@selector(pushToLoginViewController:)]) {
                [self.jsDelegate pushToLoginViewController:loginVc];
            }
        }
    }
}
-(BOOL)webView:(UIWebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(id)frame{
    UIAlertView* dialogue = [[UIAlertView alloc] initWithTitle:nil message:message delegate:self cancelButtonTitle:NSLocalizedString(@"ok", @"Ok") otherButtonTitles:NSLocalizedString(@"Cancel", @"Cancel"), nil];
    [dialogue show];
    while (dialogue.hidden==NO && dialogue.superview!=nil) {
        [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01f]];
    }
    
    return diagStat;
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        diagStat = YES;
    }else if(buttonIndex==1){
        diagStat = NO;
    }
}
- (void)setJsDelegate:(id<UIWebViewJavaScriptDelegate>)jsDelegate
{
    objc_setAssociatedObject(self, @selector(property), jsDelegate, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (id<UIWebViewJavaScriptDelegate>)jsDelegate
{
    return objc_getAssociatedObject(self, @selector(property));
}
@end
